var waiting = 5000
var sendRequest = true
const myUrl = getApp().globalData.myURL

Page({
  data: {
    target: 25,
    current: 20,
    highest: 25,
    lowest: 18
  },

  onShow: function(e) {
    wx.request({
      url: myUrl,
      data: {
        targetTemparture: -1
      },
      success: res => {
        console.log(res.data)
        let temp1 = parseFloat(res.data.split(' ')[1])
        let temp2 = parseFloat(res.data.split(' ')[0])
        if(temp1 > 0 && temp2 > 0) {
          this.setData({
            target: temp1,
            current: temp2
          })
        }
      },
      fail: err => {
        console.log(err)
      }
    })
  },

  onHide: function(e) {
    this.send(this.data.target)
  },

  upFunc: function(e) {
    wx.vibrateShort()

    let temp = this.data.target
    if(temp < this.data.highest) {
      this.setData({
        target: temp+1
      })
      this.close()
    }
    else {
      wx.showToast({
        title: '目标温度已到达上限',
        icon: 'none'
      })
    }

    if(sendRequest) {
      var that = this
      sendRequest = false
      setTimeout(() => {
        sendRequest = true
        that.send(this.data.target)
      }, waiting);
    }
  },

  downFunc: function(e) {
    wx.vibrateShort()

    let temp = this.data.target
    if(temp > this.data.lowest) {
      this.setData({
        target: temp-1
      })
      this.close()
    }
    else {
      wx.showToast({
        title: '目标温度已到达下限',
        icon: 'none'
      })
    }

    if(sendRequest) {
      var that = this
      sendRequest = false
      setTimeout(() => {
        sendRequest = true
        that.send(this.data.target)
      }, waiting);
    }
  },

  send: function(target) {
    console.log('send', target)

    wx.request({
      url: myUrl,
      data: {
        targetTemparture: target
      },
      success: res => {
        console.log(res.data)
        let temp = parseFloat(res.data.split(' ')[0])
        if(temp > 0) {
          this.setData({
            current: temp
          })
        }
      },
      fail: err => {
        console.log(err)
      }
    })
  },

  close: function(e) {
    wx.removeStorage({
      key: 'on',
    })

    wx.request({
      url: getApp().globalData.myURL,
      data: {
        targetTemparture: '--auto none'
      },
      success: res => {
        if(res.data.startsWith('success: ')) {
          console.log(res.data)
        }
        else {
          console.log('something wrong:', res.data)
        }
      },
      fail: err => {
        console.log(err)
      }
    })
  }
})